import sys
import os
from PyQt5.QtWidgets import (QWidget, QLineEdit, QPushButton, QHBoxLayout, 
                            QVBoxLayout, QApplication, QMessageBox, QMainWindow, 
                            QLabel, QFrame, QStatusBar, QSizePolicy)
from PyQt5.QtGui import QPixmap, QIcon, QCursor, QFont, QPalette, QColor
from PyQt5.QtCore import Qt, QSize, QTimer, QPropertyAnimation, QEasingCurve, pyqtSignal, QObject
from style import StyleSheet
from mail import print_mail

class ResourceManager:
    """资源管理类，负责处理应用程序的资源路径"""
    
    @staticmethod
    def get_path(relative_path):
        """获取资源文件路径，支持打包后的应用"""
        try:
            # 处理PyInstaller打包后的资源路径
            base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        except Exception:
            base_path = os.path.dirname(os.path.abspath(__file__))
        return os.path.join(base_path, relative_path)
    
    @staticmethod
    def load_pixmap(image_path, width=None, height=None):
        """加载并调整图像大小"""
        pixmap = QPixmap(ResourceManager.get_path(image_path))
        if pixmap.isNull():
            print(f"图标加载失败: {image_path}")
            return QPixmap()
        
        if width and height:
            return pixmap.scaled(width, height, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        return pixmap



class AnimationManager(QObject):
    """动画管理类，负责处理应用程序的所有动画效果"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.animations = []
    
    def create_fade_animation(self, widget, start_val=0.0, end_val=1.0, duration=1000):
        """创建淡入淡出动画"""
        animation = QPropertyAnimation(widget, b"windowOpacity")
        animation.setStartValue(start_val)
        animation.setEndValue(end_val)
        animation.setDuration(duration)
        animation.setEasingCurve(QEasingCurve.InOutQuad)
        self.animations.append(animation)
        return animation
    
    def create_scale_animation(self, widget, start_size, end_size, duration=300):
        """创建缩放动画"""
        animation = QPropertyAnimation(widget, b"size")
        animation.setStartValue(start_size)
        animation.setEndValue(end_size)
        animation.setDuration(duration)
        animation.setEasingCurve(QEasingCurve.OutQuart)
        self.animations.append(animation)
        return animation
    
    def start_animation(self, animation):
        """启动动画"""
        animation.start()

class ButtonHoverEffect:
    """按钮悬停效果类，负责处理按钮的悬停动画"""
    
    def __init__(self, button, normal_size, hover_size, duration=300):
        self.button = button
        self.normal_size = normal_size
        self.hover_size = hover_size
        self.animation_manager = AnimationManager()
        
        # 设置按钮初始大小
        self.button.setFixedSize(normal_size)
        
        # 连接事件
        self.button.enterEvent = self.on_enter
        self.button.leaveEvent = self.on_leave
    
    def on_enter(self, event):
        """鼠标进入按钮时的处理"""
        self.animation_manager.create_scale_animation(
            self.button, 
            self.normal_size, 
            self.hover_size
        ).start()
        return super(type(self.button), self.button).enterEvent(event)
    
    def on_leave(self, event):
        """鼠标离开按钮时的处理"""
        self.animation_manager.create_scale_animation(
            self.button, 
            self.hover_size, 
            self.normal_size
        ).start()
        return super(type(self.button), self.button).leaveEvent(event)

class TopLabel(QLabel):
    """顶部标题标签"""
    
    def __init__(self, text):
        super().__init__(text)
        self.setAlignment(Qt.AlignCenter)
        self.setStyleSheet(StyleSheet.TOP_LABEL)
        self.setFont(QFont("SimHei", 48, QFont.Bold))

class SearchSection(QWidget):
    """搜索区域组件"""
    
    search_triggered = pyqtSignal(str)
    tcb_triggered = pyqtSignal()
    wise_triggered = pyqtSignal()
    
    def __init__(self, width=500, height=70):
        super().__init__()
        self.init_ui(width, height)
        
    def init_ui(self, width, height):
        """初始化用户界面"""
        # 创建输入框
        self.input_field = QLineEdit(self)
        self.input_field.setPlaceholderText("请输入内容...")
        self.input_field.setFixedSize(width, height)
        self.input_field.setStyleSheet(StyleSheet.INPUT_FIELD)
        self.input_field.setFont(QFont("SimHei", 24))
        
        # 创建搜索按钮
        self.search_button = QPushButton(self)
        self.search_button.setFixedSize(80, 80)
        self.setup_search_button()
        
        # 创建TCB按钮
        self.tcb_button = QPushButton(self)
        self.tcb_button.setFixedSize(280, 150)
        self.setup_tcb_button()
        
        # 创建Wise按钮
        self.wise_button = QPushButton(self)
        self.wise_button.setFixedSize(280, 150)
        self.setup_wise_button()
        
        # 设置布局
        main_layout = QVBoxLayout()
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(0, 20, 0, 20)
        
        input_layout = QHBoxLayout()
        input_layout.addWidget(self.input_field)
        input_layout.addWidget(self.search_button)
        input_layout.setSpacing(20)
        
        button_layout = QHBoxLayout()
        button_layout.addWidget(self.tcb_button)
        button_layout.addWidget(self.wise_button)
        button_layout.setSpacing(40)
        
        main_layout.addLayout(input_layout)
        main_layout.addLayout(button_layout)
        self.setLayout(main_layout)
        
        # 连接信号
        self.search_button.clicked.connect(self.on_search_clicked)
        self.input_field.returnPressed.connect(self.on_search_clicked)
        self.tcb_button.clicked.connect(print_mail)
        self.input_field.returnPressed.connect(print_mail)
        self.wise_button.clicked.connect(self.on_wise_clicked)
    
    def setup_search_button(self):
        """设置搜索按钮"""
        pixmap = ResourceManager.load_pixmap("images/seach.png", 60, 60)
        self.search_button.setIcon(QIcon(pixmap))
        self.search_button.setIconSize(QSize(60, 60))
        self.search_button.setStyleSheet(StyleSheet.SEARCH_BUTTON)
        self.search_button.setCursor(QCursor(Qt.PointingHandCursor))
        
        # 添加悬停效果
        ButtonHoverEffect(
            self.search_button, 
            QSize(80, 80), 
            QSize(85, 85)
        )
    
    def setup_tcb_button(self):
        """设置TCB按钮"""
        pixmap = ResourceManager.load_pixmap("images/mail.png", 240, 130)
        self.tcb_button.setIcon(QIcon(pixmap))
        self.tcb_button.setIconSize(QSize(240, 130))
        self.tcb_button.setStyleSheet(StyleSheet.TCB_BUTTON)
        self.tcb_button.setCursor(QCursor(Qt.PointingHandCursor))
        
        # 添加悬停效果
        ButtonHoverEffect(
            self.tcb_button, 
            QSize(280, 150), 
            QSize(290, 160)
        )
    
    def setup_wise_button(self):
        """设置Wise按钮"""
        pixmap = ResourceManager.load_pixmap("images/wise.png", 240, 130)
        self.wise_button.setIcon(QIcon(pixmap))
        self.wise_button.setIconSize(QSize(240, 130))
        self.wise_button.setStyleSheet(StyleSheet.WISE_BUTTON)
        self.wise_button.setCursor(QCursor(Qt.PointingHandCursor))
        
        # 添加悬停效果
        ButtonHoverEffect(
            self.wise_button, 
            QSize(280, 150), 
            QSize(290, 160)
        )
    
    def on_search_clicked(self):
        """处理搜索按钮点击事件"""
        query = self.input_field.text().strip()
        if query:
            self.search_triggered.emit(query)
        else:
            self.show_warning_message("请输入搜索内容")
    
    def on_wise_clicked(self):
        """处理Wise按钮点击事件"""
        self.wise_triggered.emit()
    
    
    
    def show_warning_message(self, message):
        """显示警告消息框"""
        msg = QMessageBox()
        msg.setWindowTitle("提示")
        msg.setText(message)
        msg.setWindowIcon(QIcon(ResourceManager.get_path("images/info.png")))
        msg.setStyleSheet(StyleSheet.MESSAGE_BOX)
        msg.setFont(QFont("SimHei", 12))
        msg.exec_()

class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.animation_manager = AnimationManager()
        self.init_ui()
        
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口基本属性
        screen = QApplication.primaryScreen()
        screen_size = screen.availableGeometry()
        window_width, window_height = 1400, 900
        
        self.setWindowTitle("Mail邮箱自动化")
        self.setGeometry(
            (screen_size.width() - window_width) // 2,
            (screen_size.height() - window_height) // 2,
            window_width,
            window_height
        )
        self.setWindowIcon(QIcon(ResourceManager.get_path('my.ico')))
        self.setStyleSheet(StyleSheet.MAIN_WINDOW)
        
        # 创建背景框架
        self.background_frame = QFrame(self)
        self.background_frame.setStyleSheet(StyleSheet.BACKGROUND_FRAME)
        self.background_frame.setGeometry(0, 0, window_width, window_height)
        
        # 创建界面元素
        self.top_label = TopLabel("Mail邮箱自动化")
        self.search_section = SearchSection()
        
        # 创建底部状态栏
        self.status_bar = self.statusBar()
        self.status_bar.setStyleSheet(StyleSheet.STATUS_BAR)
        self.status_bar.setFont(QFont("SimHei", 10))
        self.status_bar.showMessage("就绪")
        
        # 设置主布局
        main_layout = QVBoxLayout()
        main_layout.setSpacing(30)
        main_layout.setContentsMargins(50, 50, 50, 50)
        
        main_layout.addWidget(self.top_label, alignment=Qt.AlignCenter)
        main_layout.addWidget(self.search_section, alignment=Qt.AlignCenter)
        main_layout.addStretch(1)
        
        central_widget = QWidget()
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)
        
        # 连接信号
        self.search_section.search_triggered.connect(self.on_search_triggered)
        self.search_section.wise_triggered.connect(self.on_wise_triggered)
        
        # 设置窗口淡入动画
        self.setWindowOpacity(0)
        fade_animation = self.animation_manager.create_fade_animation(self)
        fade_animation.start()
    
    def on_search_triggered(self, query):
        """处理搜索触发事件"""
        self.status_bar.showMessage(f"搜索: {query}")
    
    def on_wise_triggered(self):
        """处理Wise触发事件"""
        self.status_bar.showMessage("您账号未有权限")
        self.search_section.show_warning_message("您账号未有权限")

if __name__ == "__main__":
    
    
    app = QApplication(sys.argv)
    # 设置全局字体
    font = QFont("SimHei", 12)
    app.setFont(font)
    
    window = MainWindow()
    window.show()
    
    sys.exit(app.exec_())    